package servlet.rool;

import net.sf.json.JSONObject;
import pojo.Menu;
import pojo.RoMess;
import pojo.Role;
import service.MenuService;
import service.RoMessService;
import service.RoleService;
import service.impl.MenuServiceImpl;
import service.impl.RoMessServiceImpl;
import service.impl.RoleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 新增角色的servlet
 */
@WebServlet(value = "/RoleAddServlet")
public class RoleAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Role role=new Role();
        role.setRoName(request.getParameter("name"));
        role.setRoDesc(request.getParameter("desc"));
        role.setRoRool(request.getParameter("rool"));
        RoleService rs=new RoleServiceImpl();
        int bo=rs.inseRole(role);
        int bo2=0;
        JSONObject json=new JSONObject();
        if(bo>0){
            int roleId=rs.queryRoIdByName(request.getParameter("name"));
            MenuService ms=new MenuServiceImpl();
            List<Menu> menus=ms.queryMenu();
            for(Menu menu:menus){
                String menuId=request.getParameter(menu.getMeName());
                if(menuId!=null && menuId!=""){
                    RoMessService rms=new RoMessServiceImpl();
                    RoMess roMess=new RoMess();
                    roMess.setRoleId(roleId);
                    roMess.setMenuId(Integer.parseInt(menuId));
                    bo2=rms.inseRmass(roMess);
                }
            }
            if(bo2>0) {
                json.put("msg", "新增成功");
            }else {
                json.put("msg","新增失败");
            }
        }else {
            json.put("msg","新增失败");
        }
        PrintWriter out=response.getWriter();
        out.print(json);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        doGet(request, response);
    }
}
